package com.walnut.util;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

@WebFilter(dispatcherTypes = {DispatcherType.REQUEST},
        urlPatterns = "/*",
        initParams = {
                @WebInitParam(name = "excludePattern", value = "/login.jsp")
        })
public class ExcludeLoginFilter implements Filter {
    private String excludePattern;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        excludePattern = filterConfig.getInitParameter("excludePattern");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();

        // 排除静态资源请求
        if (requestURI.startsWith("/image/") || requestURI.startsWith("/css/") || requestURI.startsWith("/js/")) {
            chain.doFilter(request, response); // 直接放行静态资源请求
            return;
        }

        // 排除登录页面请求
        if (requestURI.equals(httpRequest.getContextPath() + "/login.jsp") || requestURI.equals(httpRequest.getContextPath() + "/login")) {
            chain.doFilter(request, response); // 登录页请求不需要登录验证
            return;
        }

        // 检查 ServletContext 中是否有 loginer 属性（全局登录状态）
        ServletContext context = httpRequest.getServletContext();
        String loginer = (String) context.getAttribute("loginer");

        // 如果 loginer 为 null 或为空，表示用户未登录
        if (loginer == null || loginer.isEmpty()) {
            String loginURI = httpRequest.getContextPath() + "/login.jsp";
            if (!loginURI.equals(httpRequest.getRequestURI())) {
                // 设置响应内容类型为text/html
                httpResponse.setContentType("text/html");
                // 设置HTTP状态码为403 Forbidden
                httpResponse.setStatus(HttpServletResponse.SC_FORBIDDEN);

                // 发送JavaScript代码来弹出提示窗口，并重定向到登录页面
                String htmlResponse = "<script type=\"text/javascript\">" +
                        "alert('请先登录！');" +
                        "window.location.href = '" + loginURI + "';" +
                        "</script>";

                httpResponse.getWriter().print(htmlResponse);
                return; // 终止过滤器链
            }
        }

        // 已登录用户，放行请求
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 清理代码
    }
}